﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using SelfInfo.Models;
using System.Data.Entity.Infrastructure;
using System.Data.Entity;


namespace SelfInfo.Controllers
{
    public class PieceController : Controller
    {
        private SelfInfoEntities SelfInfo = new SelfInfoEntities();

        public ActionResult Index(int id = 1, Boolean isShow = false )  // 1  is BOOK
        {

            var query = SelfInfo.TYPE.Select(c => new { c.ID, c.NAME });
            ViewData["PIECETYPE"] = new SelectList(query.AsEnumerable(), "ID", "NAME", id);
            var piece = SelfInfo.PIECE.Where(t => t.TYPE == id);
            if (isShow == false) {
                piece = piece.Where(t => t.ISSHOW == null || t.ISSHOW == true);
            }
            piece = piece.OrderByDescending(t => t.ID);
            return View(piece.ToList<PIECE>());
        }

        public ActionResult Create()
        {
            var query = SelfInfo.TYPE.Select(c => new { c.ID, c.NAME });
            ViewData["TYPE"] = new SelectList(query.AsEnumerable(), "ID", "NAME");
            return View();
        }

        [HttpPost]
        public ActionResult Create(PIECE piece)
        {

            //example
            //创建teacher一个实体
            //ITEM t = new ITEM();
            //t.TYPE = item.type;
            //t.NAME = "BOOK";
            //e.ITEM.AddObject(item);
            ////写回数据库
            //e.SaveChanges();

            if (ModelState.IsValid)
            {
                SelfInfo.PIECE.AddObject(piece);
                SelfInfo.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(piece);

        }

        public ActionResult Edit(int id)
        {

            IQueryable<PIECE> si = SelfInfo.PIECE
                           .Where(q => q.ID == id);
            var query = SelfInfo.TYPE.Select(c => new { c.ID, c.NAME });

            ViewData["TYPE"] = new SelectList(query.AsEnumerable(), "ID", "NAME", si.First().TYPE);
            return View(si.First<PIECE>());
        }

        [HttpPost]
        public ActionResult Edit(PIECE piece)
        {
           
            SelfInfo.PIECE.Attach(piece);
            SelfInfo.ObjectStateManager.ChangeObjectState(piece, System.Data.EntityState.Modified);
            SelfInfo.SaveChanges();
            return RedirectToAction("Index");
        }

    }
}
